//
//  RevanNewFeatureView.swift
//  weibo_swift
//
//  Created by 紫荆秋雪 on 17/1/10.
//  Copyright © 2017年 紫荆秋雪. All rights reserved.
//

import UIKit

class RevanNewFeatureView: UIView {
    
    // scrollView
    @IBOutlet weak var newFeatureScrollView: UIScrollView!
    // 进入微博按钮
    @IBOutlet weak var enterButton: UIButton!
    // page控制器
    @IBOutlet weak var pageControl: UIPageControl!
    
    /// 进入微博方法
    @IBAction func enterButtonClick() {
        removeFromSuperview()
    }

    /// 加载 xib 文件方法
    class func newFeature()-> RevanNewFeatureView {
        let nib = UINib(nibName: "RevanNewFeatureView", bundle: nil)
        //加载View
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! RevanNewFeatureView
        //设置frame
        v.frame = UIScreen.main.bounds
        return v
    }
    
    /// 使用代码给 xib 文件加载内容
    override func awakeFromNib() {
        // 1、通过 for 循环来给scrollview添加图片
        let count = 4
        let rect = UIScreen.main.bounds
        
        for i in 0..<count {
            // 图片名称
            let imageName = "new_feature_\(i + 1)"
            // 创建图片
            let imageView = UIImageView(image: UIImage(named: imageName))
            // 设置frame
            imageView.frame = rect.offsetBy(dx: CGFloat(i) * rect.size.width, dy: 0)
            // 添加到 scrollview 上
            newFeatureScrollView.addSubview(imageView)
        }
        
        // 2、设置scrollview
        newFeatureScrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.size.width, height: rect.height)
        newFeatureScrollView.bounces = false
        newFeatureScrollView.isPagingEnabled = true
        newFeatureScrollView.showsVerticalScrollIndicator = false
        newFeatureScrollView.showsHorizontalScrollIndicator = false
        
        // 3、设置代理
        newFeatureScrollView.delegate = self
        
        // 4、隐藏 进入微博 按钮
        enterButton.isHidden = true
    }
    
}

// MARK: - UIScrollViewDelegate
extension RevanNewFeatureView: UIScrollViewDelegate {

    // scrollView滚动减速
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 1、当前page
        let currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
        print(currentPage)
        // 2、当是 倒数第二页时，显示 进入微博按钮
        enterButton.isHidden = currentPage != scrollView.subviews.count - 1
        // 3、判断是否是 最后一页
        if currentPage == scrollView.subviews.count {
            removeFromSuperview()
        }
    }
    
    // scrollView滚动
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 隐藏 进入微博 按钮
        enterButton.isHidden = true
        // 1、获取当前页
        let currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.size.width + 0.5)
        // 2、设置pageControl的当前页
        pageControl.currentPage = currentPage
        // 3、隐藏pageControl
        pageControl.isHidden = (currentPage == scrollView.subviews.count)
    }
    
}
